package models

import (
	"encoding/json"
	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	"yixiang.co/yshop/common/untils"
	"yixiang.co/yshop/models/dto"
)

type YshopStoreProductRule struct {
	Id        int64  `json:"id"`
	RuleName  string `json:"ruleName" valid:"Required;"`
	RuleValue string `json:"ruleValue" valid:"Required;"`
	BaseModel
}

func init() {
	orm.RegisterModel(new(YshopStoreProductRule))
}

// get all
func GetAllProductRule(base dto.BasePage, query ...interface{}) (int, []dto.ProductRule) {
	var (
		tableName = "yshop_store_product_rule"
		data      []YshopStoreProductRule
		condition = ""
		retData   []dto.ProductRule
	)
	if base.Blurry != "" {
		condition = " and rule_name= '" + base.Blurry + "'"
	}

	total, _, rs := GetPagesInfo(tableName, base.Page, base.Size, condition)
	rs.QueryRows(&data)

	for _, rule := range data {
		var value []interface{}
		json.Unmarshal([]byte(rule.RuleValue), &value)
		v := dto.ProductRule{
			Id:         rule.Id,
			RuleName:   rule.RuleName,
			RuleValue:  value,
			CreateTime: rule.CreateTime,
		}

		retData = append(retData, v)
	}

	return total, retData
}

func AddProductRule(m *YshopStoreProductRule) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

func UpdateByProductRule(m *YshopStoreProductRule) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(m)
	return
}

func DelByProductRulee(ids []int64) (err error) {
	str := untils.ReturnQ(len(ids))
	logs.Info(str)
	o := orm.NewOrm()
	_, err = o.Raw("UPDATE yshop_store_product_rule SET is_del = ? WHERE id in("+str+")", 1, ids).Exec()
	return
}
